import { ConfigEnv, defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import postcssRemToResponsivePixel from 'postcss-rem-to-responsive-pixel'
import postcssWeappTailwindcssRename from 'weapp-tailwindcss-webpack-plugin/postcss'
import vue3InsetLoaderPlugin from './src/plugins/vue3-inset-loader'
import vwt from 'weapp-tailwindcss-webpack-plugin/vite'
import AutoImport from 'unplugin-auto-import/vite'

const isH5 = process.env.UNI_PLATFORM === 'h5'
const isApp = process.env.UNI_PLATFORM === 'app'
const weappTailwindcssDisabled = isH5 || isApp

const postcssPlugin = [autoprefixer(), tailwindcss()]
if (!weappTailwindcssDisabled) {
    postcssPlugin.push(
        postcssRemToResponsivePixel({
            rootValue: 32,
            propList: ['*'],
            transformUnit: 'rpx'
        })
    )
    postcssPlugin.push(postcssWeappTailwindcssRename())
}

const viteConfig = defineConfig((mode: ConfigEnv) => {
    const env = loadEnv(mode.mode, process.cwd())
    return {
        plugins: [
            vue3InsetLoaderPlugin,
            uni(),
            weappTailwindcssDisabled ? undefined : vwt(),
            AutoImport({
                imports: ['vue', 'vue-router', 'pinia', 'uni-app'], //自动引入vue的ref、toRefs、onmounted等，无需在页面中再次引入
                dts: './auto-imports.d.ts'
            })
        ],
        css: {
            postcss: {
                plugins: postcssPlugin
            }
        },
        server: {
            port: 8088,
            hmr: true, // 启用热更新
            proxy: {
                '/api': {
                    target: env.VITE_APP_BASE_URL, // 目标服务器地址
                    changeOrigin: true, // 是否修改请求头中的 Origin 字段
                    rewrite: (path: string) => {
                        const newUrl = path.replace(/^\/api/, '')
                        console.log('path', env.VITE_APP_BASE_URL, newUrl)
                        return newUrl
                    }
                }
                // "/mobile/admin": {
                //   target: env.VITE_APP_BASE_URL, // 目标服务器地址
                //   changeOrigin: true, // 是否修改请求头中的 Origin 字段
                //   rewrite: (path: string) => path.replace(/^\/mobile/, ""),
                // },
            }
        },
        build: {
            minify: 'terser', // 去除控制台输出
            terserOptions: {
                compress: {
                    drop_console: true, // 去除 console  ture 去除 false 不去除
                    drop_debugger: true // 去除 debugger
                }
            },
            rollupOptions: {
                output: {
                    manualChunks: {
                        TUIKit: ['TUIKit']
                    }
                }
            }
        }
    }
})

// https://vitejs.dev/config/
export default viteConfig
